import React from 'react';
import _ from 'underscore';
import $ from 'jquery';

import dispatcher from 'lib/dispatcher';
import { Scope } from 'lib/scopeFactory';
import TimeStore from 'lib/stores/time-store';

import { coreApi, getPropValByViewKey, propConfig } from '../apis/core-util';

export default class MainScope extends Scope {
  constructor(props, context) {
    super(props, context);
    this.$state = {
      os_views:null,
      loading: true
    };
    this.osApi = coreApi({
      urlName:'httpTopology',
      limit:null
    },TimeStore.getValue);
  }

  fetch() {
    this.osApi
        .fetch()
        .done((topoData, params) => {
          var transactions = _.chain(topoData.transaction)
                              .map((tran, n) => {
                                return {
                                  id: tran.key.id,
                                  name: tran.key.name,
                                  group: tran.key.group,
                                  avg_resp: getPropValByViewKey(tran.combData, 'avg_resp'),
                                  thp: getPropValByViewKey(tran.combData, 'thp')
                                }
                              })
                              .groupBy('group')
                              .value();

          this.$state.os_views = {
            id: topoData.id,
            name: topoData.name,
            session_count: getPropValByViewKey(topoData.session, 'session_count'),
            error_rate: getPropValByViewKey(topoData.errorRate, 'error_rate'),
            transactions: _(topoData.transaction).map((tran, n) => {
              return {
                id: tran.key.id,
                name: tran.key.name,
                group: tran.key.group,
                avg_resp: getPropValByViewKey(tran.combData, 'avg_resp'),
                thp: getPropValByViewKey(tran.combData, 'thp')
              };
            })
          };
          this.$state.loading = false;

          this.emit();
        });
  }

  $settime(payload) {
    this.$state.loading = true;
    this.emit();

    this.fetch();
  }

  $load() {
    this.fetch();
  }
}
